//
//  ModifyAvatarViewController.m
//  zhuchiren
//
//  Created by rainday on 15/1/11.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "ModifyAvatarViewController.h"
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import "MeViewModel.h"
#import <MBProgressHUD.h>
#import <UIButton+AFNetworking.h>

@interface ModifyAvatarViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic ,weak) IBOutlet UIView *navView;
@property (nonatomic ,weak) IBOutlet UIButton *selectButton;

- (IBAction)dismissSelf:(id)sender;



@end

@implementation ModifyAvatarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _navView.layer.shadowColor = [[UIColor colorWithRed:224.0/255 green:79.0/255 blue:95.0/255 alpha:1.0] CGColor];
    _navView.layer.shadowOffset = CGSizeMake(1.0, 1.0);
    _navView.layer.shadowOpacity = .3;
    
    _selectButton.layer.cornerRadius = 5;
    _selectButton.layer.masksToBounds = YES;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id avatar = [userDefaults objectForKey:@"avatar"];
    if ([avatar length]>0 && [avatar hasSuffix:@".PNG"]) {
        [_selectButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"xiangji"]];
    }else{
    
        [_selectButton setImage:[UIImage imageNamed:@"xiangji"] forState:UIControlStateNormal];
        
    }
    
    
    @weakify(self);
    [[[self.selectButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeOn:[RACScheduler mainThreadScheduler] ]subscribeNext:^(id x) {
        @strongify(self);
        
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"本地相册",@"立即拍照", nil];
        
        [actionSheet showInView:self.view];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)dismissSelf:(id)sender{
    [_delegate avatarViewController:self hasFinishedAvatar:@""];
    
}




- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    switch (buttonIndex) {
        case 0:
            
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            
            break;
        case 1:
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            break;
        default:
            break;
    }
    
    [self presentViewController:imagePickerController animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image =  [info valueForKey:@"UIImagePickerControllerOriginalImage"];
    
    CGSize size = CGSizeMake(200, 200);
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
//    NSData *dataObj = UIImageJPEGRepresentation(image, .5);
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self setAvatar:scaledImage];
    
    
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{

    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)setAvatar:(UIImage *)avatar{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = @"正在上传头像";
    [self.view addSubview:hud];
    [hud show:YES];
    @weakify(self);
    [[[MeViewModel setAvatar:avatar] subscribeOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        [[NSUserDefaults standardUserDefaults] setObject:[x objectForKey:@"avatar"] forKey:@"avatar"];
        hud.labelText = @"头像更新成功";
    
        @strongify(self);

        CGSize size = CGSizeMake(110, 110);
        UIGraphicsBeginImageContext(size);
        
        // 绘制改变大小的图片
        [avatar drawInRect:CGRectMake(0, 0, size.width, size.height)];
        // 从当前context中创建一个改变大小后的图片
        UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        // 使当前的context出堆栈
        UIGraphicsEndImageContext();
        
        [self.selectButton setImage:scaledImage forState:UIControlStateNormal];
        [hud hide:YES afterDelay:1];
        
    } error:^(NSError *error) {
        hud.labelText = @"更新失败";
        [hud hide:YES afterDelay:1];

    }];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
